from tkinter import *
import serial
import serial.tools.list_ports
import datetime
import _thread


class MainWINDOW():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name
        self.init_window_name.title("双串口调试工具")
        self.init_window_name.geometry('800x600')
        self.s = Scrollbar(self.init_window_name)
        self.text = Text(self.init_window_name, width=800, height=600)
        self.s.pack(side=RIGHT,fill=Y)
        self.text.pack(side=LEFT,fill=Y)
        self.s.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.s.set)

        self.openSerial()




    def openSerial(self):
        portlist = serial.tools.list_ports.comports()
        for port in portlist:
            print(port)
        serial1name = input("serial1name: ")
        serial2name = input("serial2name: ")
        try:
            self.serial1 = serial.Serial(serial1name, 115200)
        finally:
            print(serial1name, "Open Succeeded")

        try:
            self.serial2 = serial.Serial(serial2name, 115200)
        finally:
            print(serial2name, "Open Succeeded")
        _thread.start_new_thread(self.readserial1, ())
        _thread.start_new_thread(self.readserial2, ())

    def readserial1(self):
        while True:
            if self.serial1.in_waiting:
                self.text.insert(END, datetime.datetime.now().strftime('%H:%M:%S.%f')+" RX: "+self.serial1.readline().decode())
                self.text.see(END)
                # print(datetime.datetime.now().strftime('%H:%M:%S.%f'), "RX: ", serial1.readline())
            # if self.serial2.in_waiting:
            #     self.text.insert(END, datetime.datetime.now().strftime('%H:%M:%S.%f')+" TX: "+self.serial2.readline().decode())
            #     self.text.see(END)
    def readserial2(self):
        while True:
            if self.serial2.in_waiting:
                self.text.insert(END, datetime.datetime.now().strftime(
                    '%H:%M:%S.%f') + " TX: " + self.serial2.readline().decode())
                self.text.see(END)



def guiStart():
    my_app = Tk()
    main_window = MainWINDOW(my_app)
    my_app.mainloop()

guiStart()